
# 往数据库中添加数据，开发用

import os
import django
import random

os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'myproject.settings')

django.setup()

# django.setup()调用完成后才导入模型类
from myblog.models import Category, Tag, Post, Link
Link.objects.all().delete()
Post.objects.all().delete()
Category.objects.all().delete()
Tag.objects.all().delete()


Category.objects.bulk_create([Category(name=name) for name in ('编程语言', 'Linux', '后端', '前端', '其他')])

Tag.objects.bulk_create([Tag(name=name) for name in ('django development', 'python', 'react')])

category_list = list(Category.objects.all())

post_list = [
    Post(**{
        'title': f'title_{i}',
        'slug': f'title_{i}', # bulk_create不会调用模型的save方法，需要手动添加slug
        'subtitle': f'subtitle_{i}',
        'content': f'content_{i}',
        'category': random.choice(category_list),
        'status': Post.PUBLISHED,
    }) for i in range(30)
]
Post.objects.bulk_create(post_list)

# 多对多关系表添加数据
tag_list = list(Tag.objects.all())
for post in Post.objects.all():
    post.tags.set(random.sample(tag_list, 2))

Link.objects.bulk_create(Link(**kw) for kw in [
        {'name': 'Github', 'url': 'https://github.com/', 'ordering': 5},
        {'name': '博客园', 'url': 'https://www.cnblogs.com/', 'ordering': 4},
        {'name': '简书', 'url': 'https://www.jianshu.com/',  'ordering': 3},
        {'name': '豆瓣读书', 'url': 'https://book.douban.com/', 'ordering': 2},
        {'name': 'Gitee', 'url': 'https://gitee.com/', 'ordering': 1},
])

print("初始化数据表完成！！")